﻿using System;
using System.Threading;
using EzDesk.DesktopClient.FunctionWindowModule.ViewContract;
using EzDesk.DesktopClient.MVVMEnhance;
using EzDesk.Generic;
using EzDesk.Utility.Json;
using EzDesk.Utility.Net;
using Microsoft.Practices.Unity;

namespace EzDesk.DesktopClient.FunctionWindowModule.ViewModel
{
    public interface IActionViewModel
    {
        string IsSuccess { get; set; }
        string ResultInformation { get; set; }
        void DoAction(string url);
    }

    public class ActionViewModel : ViewModelWithSingleContainer<IActionView>, IActionViewModel
    {
        private readonly IWebRequestExt _webRequestExt;

        private string _isSuccess;

        public string IsSuccess
        {
            get { return _isSuccess; }
            set
            {
                _isSuccess = value;

                RaisePropertyChanged("IsSuccess");
            }
        }

        private string _resultInformation;
        private IDataManagement _dataManagement;

        public string ResultInformation
        {
            get { return _resultInformation; }
            set
            {
                _resultInformation = value;
                RaisePropertyChanged("ResultInformation");
            }
        }

        [InjectionConstructor]
        public ActionViewModel(IWebRequestExt webClient, IDataManagement dataManagement)
            : base()
        {
            _webRequestExt = webClient;
            _dataManagement = dataManagement;
        }

        public void DoAction(string url)
        {
            View.ShowWindowView();
            ResultInformation = "正在处理中,请稍等!";

            ThreadPool.QueueUserWorkItem(obj =>
            {
                Thread.Sleep(2000);
                DoRequest(url);
            });


            IsSuccess = string.Empty;
            ThreadPool.QueueUserWorkItem(obj =>
            {
                Thread.Sleep(2000);
                _dataManagement.RefreshDataFromServer();
            });
        }

        private void DoRequest(string url)
        {
            try
            {
                string resultJson = _webRequestExt.GetStringWithPost(url,string.Empty);
                
                var returnValue = JsonHelper.JsonToDictionary(resultJson);

                IsSuccess = returnValue["Status"] == "Success"?"操作成功":"操作失败";
                ResultInformation = returnValue["Info"];
                View.FlashShow();
            }
            catch (Exception exp)
            {
                ResultInformation = exp.Message;
                LogEx.ERROR("FunctionModule Action", exp.Message, exp);
                IsSuccess = "操作失败";
                ResultInformation = "服务连接服务器";
                View.FlashShow();
            }
        }
    }
}